package com.jiuqi.bi.metagraph.server.graph.rest;


import com.jiuqi.bi.metagraph.server.graph.MetaGraphUtil;
import com.jiuqi.bi.metagraph.server.graph.bean.CorrelationTableBean;
import com.jiuqi.bi.metagraph.server.graph.bean.EntityBean;
import com.jiuqi.bi.metagraph.server.graph.manager.MetaGraphManager;
import com.jiuqi.bi.metagraph.server.graph.query.GraphBuffer;
import com.jiuqi.bi.metagraph.server.ualog.MetagraphUALModule;
import com.jiuqi.bi.ualog.UALInfo;
import com.jiuqi.bi.ualog.UALType;
import com.jiuqi.bi.ualog.UALogger;
import org.json.JSONObject;
import org.restlet.data.Form;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;


public class GraphCorrelationResource extends ServerResource {

    /**
     * 获取前端参数：查询节点的guid、选择的关联关系类型、页容量、当前页码、选择的实体类型、输入的实体查询名称
     * keyword               一定不为空
     * relationString        一定不为空（若用户未选择，默认影响——out）
     * pageSize              一定不为空（若用户未改变，默认——10）
     * currentPage           一定不为空（若用户未改变，默认——1）
     * types                 可能为空
     * filterString          可能为空
     */
    @Override
    protected Representation post(Representation representation) throws ResourceException {
        try {
            Form form = new Form(representation);
            String keyword = form.getFirstValue("keyword");
            String relationString = form.getFirstValue("relationString");
            Integer pageSize = Integer.valueOf(form.getFirstValue("pageSize"));
            Integer currentPage = Integer.valueOf(form.getFirstValue("currentPage"));
            String types = URLDecoder.decode(form.getFirstValue("types"), StandardCharsets.UTF_8.name());
            String filterString = form.getFirstValue("filterString");
            JSONObject result = new JSONObject();

            //准备日志数据
            MetaGraphManager metaGraphManager = new MetaGraphManager();
            EntityBean keyEntity = metaGraphManager.getEntity(keyword);
            Boolean isBlood = relationString.equals("in");

            if (!MetaGraphUtil.isOpenGraph()) {
                throw new Exception("系统未开启图谱分析，不允许该操作！");
            }

            List<CorrelationTableBean> correlationTableBeans = GraphBuffer.relatedData(keyword, isBlood, types, filterString);

            //记录操作日志
            StringBuffer ualData = new StringBuffer();
            ualData.append(String.format("[%s] 图谱实体", keyEntity.getTitle()));
            ualData.append(String.format("进行 [%s] 关系查询,", isBlood ? "血缘" : "影响"));
            ualData.append("相关性查询成功");

            String ualDesc = String.format("[%s] 相关性查询。", keyEntity.getTitle());

            UALInfo ualInfo = new UALInfo(UALType.QUERY, keyEntity.getGuid(), keyEntity.getTitle(), ualData.toString(), ualDesc.toString());
            new UALogger(MetagraphUALModule.getInstance()).info(ualInfo);

            //返回分页数据
            return pagingHandler(result, correlationTableBeans, pageSize, currentPage);
        } catch (Exception e) {
            throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e.getMessage());
        }
    }


    /**
     * 分页处理器
     *
     * @param result                处理后结果
     * @param correlationTableBeans 待分页的已过滤数据
     * @param pageSize              页容量
     * @param currentPage           当前页
     * @return
     */
    StringRepresentation pagingHandler(JSONObject result, List<CorrelationTableBean> correlationTableBeans, Integer pageSize, Integer currentPage) {

        // 待分页数据集合为空（从conditionalFilter传来的null）、待分页数据集合不为空但内部没有数据(当前条件下没有找到匹配数据)
        if (correlationTableBeans == null || correlationTableBeans.isEmpty()) {
            return null;
        }
        //结果不为空
        int totalSize = correlationTableBeans.size();
        //数据量不够一页
        result.put("totalSize", totalSize);
        if (totalSize <= pageSize) {
            result.put("correlationTableBeans", correlationTableBeans);
        } else {
            int startIndex = (currentPage - 1) * pageSize;
            int endIndex = pageSize * currentPage;
            result.put("correlationTableBeans", correlationTableBeans.subList(startIndex, Math.min(endIndex, totalSize)));
        }
        return new StringRepresentation(result.toString());

    }

}
